package com.sim.server.command.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.sim.core.ImChannelContext;
import com.sim.core.ImPacket;
import com.sim.core.ImStatus;
import com.sim.core.exception.ImException;
import com.sim.core.packets.Command;
import com.sim.core.packets.RemoveUserReqBody;
import com.sim.core.packets.RespBody;
import com.sim.core.utils.JsonKit;
import com.sim.server.SimServerAPI;
import com.sim.server.command.AbstractCmdHandler;
import com.sim.server.protocol.ProtocolManager;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 踢出聊天室成员
 * @Author zl
 * @Date 2021/7/26 0026
 * @Version 1.0
 **/
public class RemoveReqHandler extends AbstractCmdHandler {

    @Override
    public Command command() {
        return Command.COMMAND_REMOVE_REQ;
    }

    @Override
    public ImPacket handler(ImPacket imPacket, ImChannelContext imChannelContext) throws ImException {
        if (imPacket.getBody() == null) {
            RespBody respBody = new RespBody(Command.COMMAND_REMOVE_RESP, ImStatus.C10031);
            return ProtocolManager.Converter.respPacket(respBody, imChannelContext);
        }
        RemoveUserReqBody reqBody = JsonKit.toBean(imPacket.getBody(), RemoveUserReqBody.class);
        String groupId = reqBody.getGroupId();
        if (StrUtil.isBlank(groupId) || CollUtil.isEmpty(reqBody.getUserIds())){
            RespBody respBody = new RespBody(Command.COMMAND_REMOVE_RESP, ImStatus.C10031);
            return ProtocolManager.Converter.respPacket(respBody, imChannelContext);
        }

        // todo 判断当前登录用户是否为该群群主，群组则有移除成员的权限

        // 将移除用户与群组解除绑定，并发送私聊
        reqBody.getUserIds().forEach(userId -> {
            boolean unbindResult = SimServerAPI.unbindGroup(userId, groupId);
            if (unbindResult){
                // 发送移除私聊通知
                Map<String, Object> result = MapUtil.builder(new HashMap<String, Object>(2))
                        .put("groupId", groupId)
                        .put("groupName", reqBody.getGroupName())
                        .build();
                ImPacket removeInfo = new ImPacket(Command.COMMAND_CHAT_REQ, new RespBody(Command.COMMAND_REMOVE_RESP, result).toByte());
                SimServerAPI.sendToUser(userId, removeInfo);
            }
        });

        RespBody respBody = new RespBody(Command.COMMAND_REMOVE_RESP, ImStatus.C10032);
        return ProtocolManager.Converter.respPacket(respBody, imChannelContext);
    }

}
